package org.spring.test;

import java.io.IOException;
import java.util.Set;

import javax.faces.context.FacesContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

/**
 * Pagina que redirecciona a la pagina de inicio de cada usuario segun el rol que tenga
 * */
public class LoginAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
		Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
		FacesContext faceContext= FacesContext.getCurrentInstance();
		if (roles.contains("USER")) {
			faceContext.getExternalContext().redirect("user/user.jsf");
		} else if (roles.contains("ADMIN")) {
			faceContext.getExternalContext().redirect("admin/admin.jsf");
		}
		faceContext.responseComplete();
	}
}
